package com.cardvalue.sys.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.cardvalue.sys.R;
import com.cardvalue.sys.base.BaseActivity;
import com.cardvalue.sys.entity.VerifyImgCode;
import com.cardvalue.sys.mode.RegService;
import com.cardvalue.sys.mode.Service;
import com.cardvalue.sys.newnetwork.Config;
import com.cardvalue.sys.tool.CheckingForm;
import com.cardvalue.sys.tool.MTextWatcher;
import com.cardvalue.sys.tool.MessageBox;
import com.cardvalue.sys.tool.Utiltools;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *注册的页面
 */

public class BindUserActivity extends BaseActivity {
    @Bind(R.id.bindMobile) EditText mobilePhone;   // 手机输入框
    @Bind(R.id.bindVertifyCode) EditText mobilePhoneVerifyCode;	 // 验证码输入框
    @Bind(R.id.bindPassword) EditText password ; 	 // 密码输入框
    @Bind(R.id.ed_inviteCode) EditText inviteCode ;   // 邀请码输入框
    @Bind(R.id.getCode) Button getCode ;  	 // 获取验证码按钮
    @Bind(R.id.bind_button) Button bind ;  	 // 注册按钮
    @Bind(R.id.textViewtk1) TextView tv;     // 确认条款url
    private Service.GetImgCode  VerifyImgCodeService;//获取图形验证码
    private Retrofit retrofit;
    private Handler handler;
    private String  imageVerifyCode;//用户输入的图形验证码
    private int codeExpirDate = 0;  // 验证码有效期
    private String  verifyCode =""; // 手机验证码
    private Timer timer=new Timer(); // 控制获取验证码按钮是否显示
    private String smsNumber ="";  //这是发送短信的手机号码
    public static boolean isRefrensh = true;//判断是否可以弹出dialog
    private String mobile;//手机号码
    private String vertify;//手机验证码
    private String  password1;//密码
    private String  inviteCode1;//邀请码
    private RegService  regService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_user);
        ButterKnife.bind(this);
        dialog=new ProgressDialog(this,R.style.dialog);
        retrofit = new Retrofit.Builder()
                .baseUrl(Config.getServerIp())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        handler=new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what==0){//图形验证码
                    getImage();
                }else if(msg.what==1){//手机验证码
                    Bundle bundle = msg.getData();
                    imageVerifyCode=bundle.get("imageVerifyCode").toString().trim();
                    getImage();
                }
            }
        };
        regService=new RegService(this);

        mobilePhone.addTextChangedListener(new MTextWatcher(){
            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() > 0 && mobilePhoneVerifyCode.length()>0  && password.length()>0){
                    bind.setBackgroundResource(R.drawable.accept_button_style);
                }else{
                    bind.setBackgroundResource(R.drawable.disabled_button_style_cc);
                }
            }
        });


        mobilePhoneVerifyCode.addTextChangedListener(new MTextWatcher(){
            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() > 0 && mobilePhone.length()>0  && password.length()>0){
                    bind.setBackgroundResource(R.drawable.accept_button_style);
                }else{
                    bind.setBackgroundResource(R.drawable.disabled_button_style_cc);
                }
            }
        });


        password.addTextChangedListener(new MTextWatcher(){
            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() > 0 && mobilePhoneVerifyCode.length()>0  && mobilePhone.length()>0){
                    bind.setBackgroundResource(R.drawable.accept_button_style);
                }else{
                    bind.setBackgroundResource(R.drawable.disabled_button_style_cc);
                }
            }
        });

    }


    @OnClick(R.id.getCode) void clickGetCode(){//获取验证码
        getImage();
    }


    @OnClick(R.id.bind_button) void clickReg(){//点击了注册按钮,要先授权
        mobile = mobilePhone.getText().toString().trim();
        vertify = mobilePhoneVerifyCode.getText().toString().trim();
        password1 = password.getText().toString().trim();
        inviteCode1=inviteCode.getText().toString().trim();
        if(!CheckingForm.checkReg(mobile,vertify,password1)){
            MessageBox.ToastShow(CheckingForm.LastError,this);
            return;
        }
        if (!mobilePhone.getText().toString().trim().equals(smsNumber)) {
            MessageBox.ToastShow("验证的手机号和您填写的手机不一致",getApplicationContext());
            return;
        }
            regService.attemptCreateAuthorization(mobile,password1,"推送id",vertify,"ip地址","reg");//授权接口
    }

    /**
     * 获取图形验证码
     */
    public void getImage(){
     if(TextUtils.isEmpty(mobilePhone.getText().toString().trim())){
         MessageBox.ToastShow("请输入手机号", this);
         return;
     }
        //发送获取验证码的请求
        VerifyImgCodeService=retrofit.create(Service.GetImgCode.class);
        VerifyImgCode verifyImgCode=new VerifyImgCode();
        smsNumber=mobilePhone.getText().toString();
        verifyImgCode.setMobilePhone(smsNumber);
        Utiltools.printE("第二次的时候是否有值：",imageVerifyCode+"hah");
        if(!TextUtils.isEmpty(imageVerifyCode)){
            verifyImgCode.setImageVerifyCode(imageVerifyCode);
        }
        Call<VerifyImgCode> repos = VerifyImgCodeService.attemptVerifyImgCode(verifyImgCode);
        repos.enqueue(new Callback<VerifyImgCode>() {
            @Override
            public void onResponse(Call<VerifyImgCode> call, Response<VerifyImgCode> response) {
                VerifyImgCode verifyImgCode=response.body();
                String error=verifyImgCode.getError()+"";
                Utiltools.printE("验证码失败后的==11=",verifyImgCode.getImgUrl()+"===url==");
                Utiltools.printE("验证码失败后的==11=",verifyImgCode.getError()+""+"===url==");
                if(!error.equals("null")){
                    MessageBox.ToastShow(verifyImgCode.getError()+"",BindUserActivity.this);
                    isRefrensh=true;
                    imageVerifyCode="";
                    return;
                }
                /**
                 * 先判断url有没有值,如果url没有值，那就说明是第二次调用，是手机验证码
                 */
                if(verifyImgCode.getImgUrl()==null){
                    MessageBox.ToastShow("验证码已发送，请注意查收", BindUserActivity.this);
                    codeExpirDate = 60; // 验证码的有效时间
                    verifyCode = "code"; // 标记已发验证码
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            updateVerifyCode();
                        }
                    },0,1000);
                }else{
                    /**
                     * 这里面又要判断dialog，是不是已经弹出来，
                     * 如果已经弹出来的话，就只要更新url中的图片
                     */
                    Utiltools.printE("验证码失败后的===",verifyImgCode.getImgUrl()+"===url==");
                    if(isRefrensh){
                        MessageBox.EditAlertReg(BindUserActivity.this,verifyImgCode.getImgUrl(),dialog,mobilePhone.getText().toString().trim(),handler);
                    }else{
                        MessageBox.setVerifyCode(BindUserActivity.this,verifyImgCode.getImgUrl());
                    }
                }
            }

            @Override
            public void onFailure(Call<VerifyImgCode> call, Throwable t) {

            }
        });
    }

    /**
     * 获取验证码倒计时
     */
    public void updateVerifyCode(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (codeExpirDate==0){
                    getCode.setText("获取验证码");
                    getCode.setEnabled(true);            //	设置按钮恢复
                    timer.cancel();                      //	取消定时器
                    timer = new Timer();
                }else{
                    if (getCode.isEnabled())
                        getCode.setEnabled(false);
                        getCode.setText("验证码("+codeExpirDate+"秒)");
                        codeExpirDate--;
                }
            }
        });
    }

}
